package com.ruitaowang.goods.service;

import com.ruitaowang.core.domain.SNSWXUserinfo;
import com.ruitaowang.core.service.BaseService;
import com.ruitaowang.goods.dao.SNSWXUserinfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * Created by neal on 11/17/16.
 */
@Service
public class WXUserinfoService implements BaseService<SNSWXUserinfo> {
    @Autowired
    private SNSWXUserinfoMapper snswxUserinfoMapper;

    @Override
    public SNSWXUserinfo insert(SNSWXUserinfo snswxUserinfo) {
        if (snswxUserinfo.getUserId() == null){
            return null;
        }
        SNSWXUserinfo origin = snswxUserinfoMapper.selectByPK(snswxUserinfo.getUserId());
        if(origin == null){
            Long time = System.currentTimeMillis();
            snswxUserinfo.setCtime(time);
            snswxUserinfo.setMtime(time);
            snswxUserinfoMapper.insert(snswxUserinfo);
        }else{
            Long time = System.currentTimeMillis();
            snswxUserinfo.setMtime(time);
            snswxUserinfoMapper.updateByPK(snswxUserinfo);
        }

        return snswxUserinfo;
    }

    @Override
    public int delete(Long id) {
        SNSWXUserinfo snswxUserinfo = new SNSWXUserinfo();
        snswxUserinfo.setUserId(id);
        snswxUserinfo.setRstatus((byte) 1);
        Long time = System.currentTimeMillis();
        snswxUserinfo.setMtime(time);
        return snswxUserinfoMapper.updateByPK(snswxUserinfo);
    }

    @Override
    public SNSWXUserinfo update(SNSWXUserinfo snswxUserinfo) {
        Long time = System.currentTimeMillis();
        snswxUserinfo.setMtime(time);
        snswxUserinfoMapper.updateByPK(snswxUserinfo);
        return snswxUserinfo;
    }

    @Override
    public SNSWXUserinfo selectByPK(Long id) {
        return snswxUserinfoMapper.selectByPK(id);
    }

    @Override
    public List<SNSWXUserinfo> select(SNSWXUserinfo snswxUserinfo) {
        snswxUserinfo.setRstatus((byte) 0);
        return snswxUserinfoMapper.select(snswxUserinfo);
    }

    public Long count() {
        SNSWXUserinfo snswxUserinfo = new SNSWXUserinfo();
        return snswxUserinfoMapper.count(snswxUserinfo);
    }
    public SNSWXUserinfo selectByOpenId(String openid){
        SNSWXUserinfo where = new SNSWXUserinfo();
        where.setOpenid(openid);
        List<SNSWXUserinfo>  infos = select(where);
        if(ObjectUtils.isEmpty(infos)){
            return null;
        }
        return infos.get(0);
    }
}
